<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="30%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #uploadIcon="{ model, field }">
        <BasicImgUpload
          :maxSize="1"
          :maxNumber="1"
          :current-value="model[field]"
          @change="handleChange"
          :api="uploadApi"
          class="my-5"
          :accept="['image/*']"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicImgUpload } from '/@/components/Upload';
  import { uploadApi } from '/@/api/sys/upload';
  import { formSchema } from './category.data';
  import { getCategoryList, saveOrUpdate } from './category.api';

  export default defineComponent({
    name: 'CategoryDrawer',
    components: { BasicDrawer, BasicForm, BasicImgUpload },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);

      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 120,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
          setFieldsValue({
            commissionRate: data.record.commissionRate * 100,
          });
        } else {
          setFieldsValue({
            parentId: data.record.parentId,
          });
        }
        const treeData = await getCategoryList({});
        updateSchema({
          field: 'parentId',
          componentProps: { treeData },
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增商品分类' : '编辑商品分类'));

      async function handleSubmit() {
        try {
          const values = await validate();
          values.commissionRate = values.commissionRate / 100;
          setDrawerProps({ confirmLoading: true });
          await saveOrUpdate(values, isUpdate.value);
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      const handleChange = (imgUrl) => {
        setFieldsValue({
          image: imgUrl,
        });
      };

      return {
        registerDrawer,
        registerForm,
        handleSubmit,
        handleChange,
        uploadApi,
        getTitle,
      };
    },
  });
</script>
